package io.netty.custom.websocket.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <p>
 * 保存uid和ChannelId
 * </p>
 *
 * @author gobigg
 * @since 2022/1/20
 */
public class ChannelHolder {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static ConcurrentMap<String, ChannelId> channelIdMap = new ConcurrentHashMap();

    public static void addChannel(String uid, Channel channel) {
        channelGroup.add(channel);
        channelIdMap.put(uid, channel.id());
    }

    public static void removeChannel(String uid, Channel channel) {
        channelGroup.remove(channel);
        channelIdMap.remove(uid);
    }

    public static Channel findChannel(String uid) {
        if (channelIdMap.get(uid) == null) {
            return null;
        }
        return channelGroup.find(channelIdMap.get(uid));
    }

    public static void send2All(TextWebSocketFrame tws) {
        channelGroup.writeAndFlush(tws);
    }

    public static ConcurrentMap<String, ChannelId> getChannelMap() {
        return channelIdMap;
    }
}
